package com.fwtai.service.api;

import com.fwtai.api.ApiMallDao;
import com.fwtai.bean.PageFormData;
import com.fwtai.service.AsyncService;
import com.fwtai.tool.ToolClient;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
public class ApiMallService{

  private final ApiMallDao apiMallDao;

  private final AsyncService asyncService;

  private final ThreadPoolTaskExecutor taskExecutor;

  public ApiMallService(final ApiMallDao apiMallDao,final AsyncService asyncService,final ThreadPoolTaskExecutor taskExecutor){
    this.apiMallDao = apiMallDao;
    this.asyncService = asyncService;
    this.taskExecutor = taskExecutor;
  }

  public String listMallGoods(final HttpServletRequest request){
    return CompletableFuture.supplyAsync(()->{
      final PageFormData formData = ToolClient.pageParamsApi(request);
      if(formData == null){
        return ToolClient.jsonValidateField();
      }
      final List<HashMap<String,Object>> list = apiMallDao.listMallGoods(formData);
      final HashMap<String,Object> result = new HashMap<>(2);
      if(!list.isEmpty()){
        result.put("listGoods",list);
        final List<Long> kids = list.stream().map(map -> (Long) map.get("kid")).collect(Collectors.toList());
        final List<HashMap<String,Object>> listSpec = apiMallDao.getGoodsSpec(kids);
        if(!listSpec.isEmpty()){
          result.put("listSpec",listSpec);
        }
      }
      return ToolClient.jsonPage(result,list.size());
    },taskExecutor).join();
  }

  public String getGoodsInfo(final Long kid){
    return CompletableFuture.supplyAsync(()->{
      if(kid == null){
        return ToolClient.jsonValidateField();
      }
      return CompletableFuture.supplyAsync(()-> apiMallDao.getGoodsInfo(kid),taskExecutor).thenApply((map) -> {
        if(map == null) return ToolClient.createJsonFail("数据不存在,刷新重试");
        asyncService.updateGoodsPv(kid,taskExecutor);//更新浏览量
        //此处是查询一对多
        final List<HashMap<String,Object>> list = CompletableFuture.supplyAsync(()-> apiMallDao.queryList(kid),taskExecutor).join();
        if(!list.isEmpty()){
          map.put("list",list);
        }
        return ToolClient.queryJson(map);
      }).join();
    },taskExecutor).join();
  }

  public String getGoodsCategory(){
    return CompletableFuture.supplyAsync(()->{
      return ToolClient.queryJson(apiMallDao.getGoodsCategory());
    },taskExecutor).join();
  }
}